<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div>
    <p id="name"></p>
    <p id="age"></p>
    <p id="idCard"></p>
    <p id="address"></p>
    <p id="test"></p>
    <p id="arr"></p>
  </div>
  <script>
    // 数据
    const data = {
      name: '张三',
      age: 19,
      info: {
        idCard: 233455667889001223,
        address: '下沙'
      },
      arr: [1,2,3]
    }

    // 同步视图的方法
    function setView() {
      document.getElementById('name').innerHTML = data.name 
      document.getElementById('age').innerHTML = data.age 
      document.getElementById('idCard').innerHTML = data.info.idCard 
      document.getElementById('address').innerHTML = data.info.address 
      document.getElementById('test').innerHTML = data.test
      document.getElementById('arr').innerHTML = data.arr[1]
    }
    setView()

    observer(data)

    // 递归的方法
    function observer(data) {
      Object.keys(data).forEach(key => {
        if (typeof data[key] === 'object') {
          return observer(data[key])
        }
        let getValue = data[key]
        Object.defineProperty(data, key, {
          get () {
            return getValue
          },
          set (val) {
            getValue = val
            setView()
          }
        })
      })
    }
  </script>
</body>
</html>